#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
games.py

channels only for channels
chanlang translation if channel language
wherelang search only if channel language
"""
import codecs, os, random, re, time
if __name__ != '__main__':
	from core.ircfuncs import not_on_channel
	from core.optimizers import _path
field = "game"

def ping__(bot, evt, cmd):
	if cmd.dict["cmd"]:
		print evt.msg
		ping = cmd.dict["cmd"]
		ping=ping.replace("i","o")
		ping=ping.replace("I","O")
		ping=ping.replace("1","0")
		if not evt.stalked:
			ping="$nick: %s" % (ping)
		bot._pingbuffer = (evt.target, ping)
		bot.ctcp(evt.source, "PING %s" % (time.time()))
ping__.rule = re.compile("^(?i)($both)?(?P<cmd>p[i1]ng!?)$")
ping__.fullmsg = True

def ping_reply(bot, evt, cmd):
	if evt.ctcp[0]=="ping":
		t1 = time.time(); t2 = float(evt.ctcp[1])
		diff = t1 - t2
		d = ("%.3f" %diff).split(".")
		c = "%s s %s ms" %(d[0], d[1])
		if hasattr(bot, "_pingbuffer") and bot._pingbuffer:
			t = bot._pingbuffer[0]
			m = bot._pingbuffer[1]
			msg = "%s || %s" %(m, c)
			bot.privmsg(t, msg)
			del bot._pingbuffer
			return
		else:
			diff = (t1-1333152000) - t2
			d = ("%.3f" %diff).split(".")
			c = "%s s %s ms" %(d[0], d[1])
		bot.priv_msg(evt, "$nick PING: %s", c)
ping_reply.rule = "ctcp"
ping_reply.evttypes= ["ctcp"]

def randkick(bot, evt, cmd):
	ops = bot.channels[canal].opers()
	deop=False
	if self.nickname not in ops:
		deop=True
		#OP is asynchronous
		bot.chanserv("OP $chan $me")
		time.sleep(1)
	if check_access(bot, "admin") or evt.target in ("##bots-ca",): #,"#wikipedia-ca"):
		dontkick = ["kibble","toniher"]
		dontkick += ops

		for n in bot.channels[canal].voiced():
			if n not in dontkick: dontkick.append(n)

		kickable = []; msg = ""
		if cmd.cmdline:
			if ":" in cmd.cmdline:
				msg = cmd.cmdline.split(":",1)
				kicklist = msg[0].split(",")
				msg = msg[1]
			elif "," in args:
				kicklist = cmd.cmdline.split(",")
			for user in kicklist:
				user = user.split()[0]
				if user in bot.channels[evt.target].users():
					kickable.append(user)
		if not kickable:
			for user in self.channels[canal].users():
				if user not in dontkick:
					kickable.append(user.strip())
		if kickable:
			kicked = random.choice(kickable)
			if not msg: "random kick, please read better the topic"
			bot.kick(evt.target, kicked, msg.encode("utf8"))
		else:
			bot.reply(evt, "No es pot patejar ningun dels usuaris presents. Proveu-ho en un altre canal")
	else:
		time.sleep(random.randint(1,5))
		bot.reply(evt, "No s'ha pogut realitzar l'acció seleccionada, sisplau trieu una altra")
	if deop:
		time.sleep(1)
		bot.chanserv("DEOP $chan $me")
randkick.rule = "randkick"

def euromilions(bot, evt, cmd):
	n=[]
	while len(n)<5:
		x = random.randint(2,51)-1
		if x not in n:
			n.append(x)
	s=[]
	while len(s)<2:
		x = random.randint(2,10)-1
		if x not in s:
			s.append(x)
	msg = "%s | %s" % (", ".join([str(x) for x in n]), ", ".join([str(x) for x in s]))
	bot.reply(evt, msg)
euromilions.rule = re.compile(ur"(?#re)^($both)(?:[€e]uromil(?:l?ions|lones)|€)$")
euromilions.fullmsg = True

def cookie(bot, evt, cmd):
	print __name__, "cookie"
	c=os.popen("fortune")
	recurs=c.readlines()
	c.close()
	for r in recurs:
		bot.reply(evt, r)
		time.sleep(1.0)
cookie.rule = re.compile(ur"(?#re)^($both)(?:ga(?:lleti|lete)ta|cookie)$")
cookie.fullmsg = True

def wtf(bot, evt, cmd):
	call = "wtf %s" % cmd.arguments
	c=os.popen(call)
	recurs=c.readlines()
	c.close()
	for r in recurs:
		bot.reply(evt, r)
		time.sleep(1.0)
wtf.rule = "wtf"

def is42_(bot, evt, cmd):
	bot.reply(evt, "42")
is42_.rule = "=answer to life the universe and everything"
is42_.fullmsg = True

def day(bot, evt, cmd):
	bot.reply(evt, time.strftime("%d-%m%Y"))
day.rule = ["data", "dia"]

def hour(bot, evt, cmd):
	bot.reply(evt, time.strftime("%H:%M"))
hour.rule = ["hour", "hora"]

def coffee_(bot, evt, cmd):
	bot.choose_reply(evt, bot.replies.coffee,100)
coffee_.rule = ["cafe", "coffee", u"cafè", u"café"]

def cigarrette_(bot, evt, cmd):
	bot.choose_reply(evt, bot.replies.cigarrette,100)
cigarrette_.rule = ["cigarrette", "cigarreta", "tobacco"]

def joint_(bot, evt, cmd):
	bot.choose_reply(evt, bot.replies.joint,100)
joint_.rule = ["joint","porro"]

def beer_(bot, evt, cmd):
	bot.choose_reply(evt, bot.replies.beer,100)
beer_.rule = re.compile(ur"litrona|cervesa|birra")

def gorgeous_(bot, evt, cmd):
	bot.choose_reply(evt, bot.replies.gorgeous,100)
gorgeous_.rule = ["guapo", "beautiful", "biutiful"]

def sexy_(bot, evt, cmd):
	bot.choose_reply(evt, bot.replies.sexy,100)
sexy_.rule = "sexy"

def arrows(bot, evt, cmd):
	bot.reply(evt, u"→ ← ↔ ↑ ↓ ↕ ↗ ↘ ↙ ↖")
arrows.rule = "arr"

"""
		elif ordre == "mes":
			call="cal -m3"
			c=os.popen(call)
			recurs=c.readlines()
			c.close()
			for i in recurs:
				bot.reply(evt, i)
				time.sleep(2.0)
			m = time.strftime("%m")
			months={
				1: "gener", 2: "febrer", 3: "març", 4: "abril", 5: "maig", 6: "juny",
				7: "juliol", 8: "agost", 9: "setembre", 10: "octubre", 11: "novembre", 12: "desembre"
			}
			m=months[int(m)]
			bot.reply(evt, m)
"""

def clever_(bot, evt, cmd):
	bot.choose_reply(evt, bot.replies.clever,100)
clever_.rule = re.compile(ur"(?#re)^(?:$both)(?:llest|intel(?:(?:·|.)l)?igent|clever|listo)")
clever_.fullmsg = True

def test_(bot, evt, cmd):
	bot.reply(evt, "hello Moto!")
test_.rule ="test"

def inlove_(bot, evt, cmd):
	bot.reply(evt, "^_^")
inlove_.rule = re.compile("^@_@$")
inlove_.fullmsg = True

def sodom_(bot, evt, cmd):
	if not_on_channel(bot, "##pampolut"): return
	call= u"cowthink -f sodomized %s" % cmd.arguments
	a=os.popen(llamada)
	recurs=a.readlines()
	a.close()
	salida=""
	for i in recurs:
		bot.reply(evt, i)
		time.sleep(2.0)
sodom_.rule = "fool"

def weiser_(bat, evt, cmd):
	msg = random.choice([">:D si l'agarre me'l menge!!!","0_0 on? tireu-lo!!!", "B) HEU DIT WEISER o_O", "sisplau no pronuncieu més este nom","/KICK WEISER!!!"])
	bot.reply(evt, msg)
weiser_.rule = "weiser"
weiser_.fullmsg = True
weiser_.wherelang = "ca"

def comandes_(bot, evt, cmd):
	#comandes no vol dir ordres! xD SMP sempre s'enganya!
	bot.reply(evt, u"DIEC: comanda:  f. [LC] Encàrrec")
	bot.reply(evt, u"esteu intentant aconseguir una llista de totes les @ordres? :P")
comandes_.rule = re.compile(r"comand[eo]?s")
comandes_.wherelang = "ca"

def strsize(bot, evt, cmd):
	bot.reply(evt, u"string contains &t;%i&N; characters.", len(cmd.arguments))
strsize.rule = "strsize"
strsize.chanlang = {"ca": "compta"}

def funny_(bot, evt, cmd):
	bot.reply(evt, "it doesn't :(")
funny_.rule = re.compile("^(?:it rocks)$")
funny_.chanlang = {"ca": re.compile("(?#re)^mola$"), "es": re.compile("(?#re)^mola$")}
funny_.fullmsg = True

def heyguy_(bot, evt, cmd):
	bot.reply(evt, "què pesat!")
heyguy_.rule = re.compile(ur"(?#re)^h?e[iy] (guy|t[íi]o)$")
heyguy_.fullmsg = True

def favmeal_(bot, evt, cmd):
	bot.reply(evt, "XD")
favmeal_.rule = "poma"
favmeal_.priority = "low"
favmeal_.fullmsg = True

def deprfavcmeal_(bot, evt, cmd):
	bot.reply(evt, "poma!")
deprfavcmeal_.rule = re.compile(ur"\bmel[óo]\b")
deprfavcmeal_.fullmsg = True

def goingtoeat_(bot, evt, cmd):
	time.sleep(random.randint(0,3))
	bot.reply(evt, "Profit!")
goingtoeat_.rule = re.compile(ur"((m\'?e\'?n )?vaig a (sop|din)ar)")
goingtoeat_.wherelang = "ca"

def	goingtobed_(bot, evt, cmd):
	dice = random.randint(0,3)
	time.sleep(dice)
	nick  =  evt.source.lower()
	if not usuarisAcomiadats.has_key(nick) or (usuarisAcomiadats.has_key(nick) and int(time.time()) - usuarisAcomiadats[nick] > 60):
		usuarisAcomiadats.update({nick: int(time.time())})
	if usuarisAcomiadats.has_key(nick) and int(time.time()) == usuarisAcomiadats[nick]:
		msg="Bona nit!"
		if dau == 2:
			msg=msg.replace("o","O")
		if dau == 3:
			msg=msg.lower().replace("!", " %s!" % nick)
		bot.reply(evt, msg)
re.compile(ur"((bo)?na ?nit|m\'?e\'?n vaig (a dormir|al llit))")
goingtobed_.wherelang = "ca"

def goodbye_(bot, evt, cmd):
	if re.search(ur"ad?[ée]u|\bd1\b|\ba10\b|\ba?dew+\b|m'?e'?n vaig|(?:m'en |me'n|me n')he d'anar|marxo|ja (?:ens|mos) v(?:eu|o)rem|fins (?:aviat|despr[éèe]s)|pass(?:i|eu)-?ho(?:-?vos)? bé", ev_args.lower()):
				esUnAltreUsuari=False
				nickComiat = nick #se suposa qu qui parla se'n va
				usrList = self.channels[canal].users() if canal in self.channels.keys() else []
				#llistem els usuaris
				usuaris= []
				for usr in usrList:
					usuaris.append(usr.lower())
				lligMsg=ev_args.lower()
				lligMsg=lligMsg.split(" ")
				#busquem que no hi haja coincidències
				for mot in lligMsg:
					if mot in usuaris and mot not in usuarisAcomiadats.keys():
						esUnAltreUsuari=True
						nickComiat=mot #se suposa que qui parla acomiada algu que marxa
						usuarisAcomiadats.setdefault(nickComiat.lower(),int(time.time()))
				if not usuarisAcomiadats.has_key(nickComiat.lower()) or (usuarisAcomiadats.has_key(nick) and int(time.time()) - usuarisAcomiadats[nick] > 60):
					usuarisAcomiadats[nickComiat.lower()]=int(time.time())
				if int(time.time()) == usuarisAcomiadats[nickComiat.lower()] or esUnAltreUsuari:
					if not esUnAltreUsuari:
						bot.choose_reply(evt, bot.replies.comiat,100,c,canal,(nick,))
					else:
						bot.choose_reply(evt, bot.replies.unaltrecomiat,100,c,canal,(nick,))
goodbye_.wherelang = "ca"

def vec(bot, evt, cmd):
	if re.search("[^!][\.@](?:vnd|vec)", ev_args, re.I):
				link="http://ca.wikipedia.org/wiki/Viquip%C3%A8dia:Observatori_del_vandalisme/Avisos_autom%C3%A0tics#footer"
				bot.reply(evt, link)

def jajaja_(bot, evt, cmd):
	if bot.current_nname != "geni" and "geni" in bot.channels[evt.chan].users(): return True
	chunk0=re.search("((j[aeiou]){2,})", evt.msg, re.I).group(1)
	chunk1=chunk0.lower().replace("j", "h")
	if chunk0.isupper(): chunk1 = chunk1.upper()
	bot.reply(evt, "$nick: canvia %s per %s " % (chunk0[:6], chunk1.replace("j", "h")[:6]))
jajaja_.rule = re.compile("(j[aeiou]){2,}")
jajaja_.fullmsg = True
jajaja_.wherelang = "ca"

def alea(bot, evt, cmd):
   """.random <experssion> - alea jacta est."""
   params = cmd.arguments
   result = ""
   if params:
      b=[]
      if ", " in params:
         b=params.split(", ")
      elif "," in params:
         b=params.split(",")
      if len(b)==2 and b[0].isdigit() and b[1].isdigit():
         #random numbers are generated by decimal number, obviously a @ran 0,1 always gets 1
         #add 1 always and later substract it
         b=[int(b[0])+1,int(b[1])+1]
         if b[0]>b[1]:
            b=[b[1],b[0]]
         b=random.randint(b[0],b[1])-1
         result = str(b)
      elif len(b)>1:
         choice=random.choice(b)
         result=choice.encode("utf-8")
      else:
         result="el número de opciones es insuficiente."
   else:
      b=random.randint(1,2)
      if b==1:
         result="odds" #senars
      else:
         result= "even" #"parells"
   if result:
      bot.reply(evt, result)
alea.rule = ['rand','random', "rnd", "shuffle"]
alea.chanlang = {"ca": "alea"}

def joke(bot, evt, cmd):
	""".joke - envía algo gracioso, se supone."""
	jokedir = _path.join(_path.home, 'speech', "chistes")
	fs =["chikito","chistes","colmos","definiciones","feministas",
		 "habia","jaimito","mama","tags","verdes"]
	f = random.choice(fs)
	f += ".txt"
	f = codecs.open(_path.join(jokedir, f), "r", "cp1252")
	txt = f.read()
	f.close()
	lines = txt.splitlines()
	joke = random.choice(lines)
	bot.reply(evt, joke)
joke.rule = 'joke'
joke.chanlang = {"ca": 'acudit', "es": 'chiste'}

def quote(self, origin, args):
	""".dialgo - algo hará..."""
	jokedir = _path.join(_path.home, 'speech', "chistes")
	fs =_path.files(jokedir)
	f = random.choice(fs)
	f = codecs.open(_path.join(jokedir, f), "r", "cp1252")
	txt = f.read()
	f.close()
	lines = txt.splitlines()
	line = random.choice(lines)
	bot.reply(evt, origin.target, line)
quote.rule = ['quote','dialgo']
quote.showas = "quote|dialgo"

def selquote(bot, evt, cmd):
	""".selquote {citas|chistes|verdes|filosofia|discri|estupido|piropos|refranes}"""
	#folders by topic
	matrix={"citas": ["citas"],
			"chistes": [
				"chikito","chistes","colmos","definiciones",
				"feministas","habia","jaimito",
				"mama","tags","verdes","win95"
			],
			"verde": ["verdes"],
			"filosofia": ["filosofa"],
			"discri": ["gallegos","Lepe","rubias","si_ella"],
			"estupido": ["estupido","Tonto","tumadre"],
			"piropos": ["piropos"],
			"refranes": ["refranero"]
			}
	jokedir = _path.join(_path.home, 'speech', "chistes")
	choosen = cmd.arguments

	#aliases
	if choosen in [u"filosofía","filosofia"]: choosen= "filosofia"
	elif choosen in ["cita", "quote"]: choosen = "citas"
	elif choosen=="chiste": choosen = "chistes"
	elif choosen in ["refran", "refranero","refranes", u"refrán"]: choosen = "refranes"
	elif choosen in ["piropo","cursi"]: choosen = "piropos"
	elif choosen in ["dicriminatorio"]: choosen = "discri"
	elif choosen in ["verde","verdes","sexo","guarro"]: choosen = "verde"

	if choosen not in matrix: choosen = random.choice(matrix.keys())

	f = random.choice(matrix[choosen])
	f += ".txt"
	f = codecs.open(_path.join(jokedir, f), "r", "cp1252")
	lines = f.readlines()
	f.close()
	choice = random.choice(lines)
	bot.reply(evt, choice)
selquote.rule = 'selquote'
selquote.showas = "selquote"
selquote.chanlang = {"es": ["elige", "eligechiste"]}

def fetch_line_(bot, evt, cmd):
	folder = _path.join(_path.home, 'speech', "chistes")
	fname = cmd.opts['f'] or cmd.opts['file']
	fname += ".txt"
	f = codecs.open(_path.join(folder, fname), "r", "cp1252")
	lines = f.readlines()
	f.close()
	line = cmd.opts['l'] or cmd.opts['line']
	line = int(line)-1
	bot.reply(evt, lines[line])
fetch_line_.rule = "fl"

if __name__ == "__main__":
   import os, codecs
   dirs = os.getcwd().split(os.path.sep)
   main_dir = os.sep.join(dirs[:-2])
   jokedir = os.path.join(main_dir, 'speech', 'chistes')
   files = os.listdir(jokedir)
   filename = os.path.join(jokedir, random.choice(files))
   f = codecs.open(filename, "r")
   joke = random.choice(f.read().splitlines())
   f.close()
   print "%s:\n" % filename, joke
